<template>
  <div>
    <Loading v-show="$store.state.isLoading" />
    <div v-show="!$store.state.isLoading">
      <div class="wrapper" v-show="$route.path == '/detail'">
        <bookHeader> 书籍详情 </bookHeader>
        <div class="bookinfo" v-if="info">
          <div class="top">
            <div class="l">
              <img :src="info.cover" alt="" />
            </div>
            <div class="r">
              <div class="title">{{ info.title }}</div>
              <div class="author" v-if="detail">
                <span style="margin-right: 5px"> {{ detail.category }}</span
                >|<span
                  style="color: skyblue; margin-left: 5px; font-size: 15px"
                  >{{ info.author }}</span
                >
              </div>
              <div class="rate">
                <van-rate
                  v-model="rateVal"
                  :size="14"
                  color="#ffd21e"
                  void-icon="star"
                  void-color="#ff5000"
                />
              </div>
              <div class="word">
                <span class="words">{{ detail.words | filterWords }}万字</span>
                <span class="clicks">{{ detail.clicksCount }}点击</span>
              </div>
              <div class="wprice">
                <div v-if="detail.wprice">{{ detail.wprice }}阅点/千字</div>
                <div v-else style="color: red">{{ detail.price }}阅点</div>
              </div>
            </div>
          </div>
          <div class="bottom">
            <div :class="show == false ? 'content' : 'content hidden'">
              {{ detail.content.text }}
              <van-icon name="arrow-down" @click.stop="isShow" v-show="show" />
              <div class="type">作品类型:{{ detail.paydesc }}</div>
            </div>
          </div>
          <div class="mulu" @click="gotomulu">
            <div class="l">
              <van-icon
                class="iconfont"
                class-prefix="icon"
                name="mulu"
              ></van-icon>
            </div>
            <div class="c">
              <div v-if="detail.wprice">
                {{ detail.updated | UpdateDate }} 更至:第{{
                  detail.totalArticleCount[0]
                }}章
              </div>
              <div v-else>共{{ detail.totalArticleCount[0] }}章</div>
            </div>
            <div class="r">
              <div v-if="(detail.price = 0)">连载中</div>
              <van-icon name="arrow" size="16" />
            </div>
          </div>
        </div>
        <div class="comment">
          <div class="header">
            <div class="l">评论</div>
            <div class="r" v-show="list.length > 0" @click="writeComment">
              <span class="iconfont icon-xiepinglun"></span>
              写评论
            </div>
          </div>
          <commentList :list="list.slice(0, 5)"></commentList>
          <div v-if="list.length == 0" class="write-comment">
            <div>快来当第一个写评论的人吧</div>
            <button class="write" @click="writeComment">写评论</button>
          </div>
          <div class="all" @click="gotoAllcomment" v-else>查看全部评论</div>
        </div>
        <bookBottomControl
          @addBooshelf="addBooshelf"
          :addBook="addBook"
          @gotoContent="gotoContent"
        ></bookBottomControl>
      </div>
      <transition
        v-show="$route.path == '/detail/comment'"
        leave-active-class="animate__animated animate__slideOutRight"
      >
        <router-view :list="list" />
      </transition>
      <transition
        v-show="$route.path == '/detail/login'"
        leave-active-class="animate__animated animate__slideOutRight"
      >
        <router-view />
      </transition>
    </div>
    <van-popup v-model="isShowPop" position="bottom" :style="{ height: '30%' }">
      <div class="write_comment">
        <div class="rate-container">
          评分:
          <van-rate
            v-model="grade"
            :size="30"
            color="#ffd21e"
            void-icon="star"
            void-color="#ccc"
            @change="onRateChange"
          />
        </div>
        <div class="write_content">
          <textarea
            style="font-size: 16px"
            v-model="comment_msg"
            placeholder=""
          ></textarea>
        </div>
        <div class="control">
          <p>{{ length }}字</p>
          <van-button type="danger" size="small" @click="saveComment"
            >发送</van-button
          >
        </div>
      </div>
    </van-popup>
  </div>
</template>

<script>
import { bookDetailInfo, bookDetail, bookcommentList } from "@/request/api";
import bookHeader from "@/components/bookHeader";
import commentList from "@/components/commentList";
import bookBottomControl from "@/components/bookBottomControl";

export default {
  name: "Xiangqing",
  components: {
    bookHeader,
    commentList,
    bookBottomControl,
  },
  data() {
    return {
      info: null,
      detail: {
        content: "",
        category: "",
        totalArticleCount: [],
        updated: "",
        words: "",
        wprice: "",
        clicksCount: "",
        //作品类型
        paydesc: "",
        price: "",
      },
      comment: {
        list: [],
        next: "",
      },
      booID: "-1",
      show: true,
      rateVal: 5,
      addBook: {
        isAdd: false,
        text: "加入书架",
      },
      //底部弹出层
      isShowPop: false,
      //grade 评分
      grade: 5,
      //评论内容
      comment_msg: "",
      //评论对象
      commentObj: {},
    };
  },
  watch: {
    booID(newVal, oldVal) {
      this.commentObj.bookID = newVal;
      this.booisAdd(newVal);
    },
    comment_msg(newVal) {
      this.commentObj.comment = newVal;
    },
  },
  computed: {
    length() {
      return this.comment_msg.length;
    },
    list() {
      return this.comment.list;
    },
  },
  filters: {
    filterWords(val) {
      return Math.round(val / 10000);
    },
    UpdateDate(val) {
      let d = new Date(val);
      return d.getMonth() + 1 + "月" + d.getDate() + "号";
    },
  },
  methods: {
    //监听评分改变
    onRateChange(val) {
      this.grade = val;
    },
    //发送评论
    saveComment() {
      this.commentObj.grade = this.grade;
      this.commentObj.avatar = this.$store.state.userInfo.avatar;
      this.commentObj.nickName = this.$store.state.userInfo.nickname;
      this.commentObj.time = Date.now();

      this.commentObj.commentId = Math.random() * 10000;
      let list = JSON.parse(localStorage.getItem("yunread-comment")) || [];
      list.push(this.commentObj);
      localStorage.setItem("yunread-comment", JSON.stringify(list));
      this.isShowPop = false;
      this.getPublishComment();
    },
    //判断书本是否在书架中
    booisAdd(booID) {
      let bookIDS = JSON.parse(localStorage.getItem("bookIDS")) || [];
      let index = bookIDS.findIndex((v) => v == booID);
      if (index != -1) {
        this.addBook.isAdd = true;
        this.addBook.text = "已在书架";
      } else {
        this.addBook.isAdd = false;
        this.addBook.text = "加入书架";
      }
    },
    //写评论
    writeComment() {
      if (!this.$store.state.token) {
        this.$dialog
          .confirm({
            message: "尚未登录!是否去登录一下?",
          })
          .then(() => {
            this.$router.push({ path: "/detail/login" });
            this.$forceUpdate();
          })
          .catch(() => {
            // on cancel
          });
      } else {
        this.isShowPop = true;
      }
    },

    //处理加入书架事件
    addBooshelf() {
      let id = this.$route.query.sourceUuid;
      let bookIDS = JSON.parse(localStorage.getItem("bookIDS")) || [];
      let index = bookIDS.findIndex((v) => v == id);
      if (index != -1) {
        return;
      }
      bookIDS.unshift(id);
      localStorage.setItem("bookIDS", JSON.stringify(bookIDS));
      this.$forceUpdate();
    },
    //去内容页
    gotoContent() {
      this.$router.push(
        "/content?source_uuid=" +
          this.$route.query.sourceUuid +
          "&title=" +
          this.info.title
      );
    },
    //去所有评论页面
    gotoAllcomment() {
      this.$router.push("/detail/comment");
    },
    //是否展示全部介绍
    isShow() {
      this.show = false;
    },
    //点击目录跳转去目录页面
    gotomulu() {
      this.$router.push("/chapter?source_uuid=" + this.$route.query.sourceUuid);
    },
    //获取该书本的全部评论
    async getComments() {
      let { all } = await bookcommentList({
        bookId: this.$route.query.sourceUuid,
      });
      this.comment.list = all.list;
      this.getPublishComment();
    },
    //获取发布的评论
    getPublishComment() {
      let list = JSON.parse(localStorage.getItem("yunread-comment")) || [];
      if (list.length > 0) {
        list.map((v) => {
          if (v.bookID == this.$route.query.sourceUuid) {
            this.list.unshift(v);
          }
        });
      }
    },
    //获取书本详情
    async getBookInfo() {
      let {
        data: { book },
      } = await bookDetailInfo({
        sourceUuid: this.$route.query.sourceUuid,
      });
      this.info = book;
      let { feed } = await bookDetail({
        id: this.$route.query.sourceUuid,
        title: this.info.title,
      });
      this.detail.content = feed.entry.content;
      this.detail.category = feed.entry["pris:book"].category;
      this.detail.totalArticleCount = feed.entry["pris:book"].totalArticleCount;
      this.detail.updated = feed.entry["pris:book"].updated;
      this.detail.words = feed.entry["pris:book"].words;
      this.detail.wprice = feed.entry["pris:book"].wprice;
      this.detail.price = feed.entry["pris:book"].price;
      this.detail.paydesc = feed.entry["pris:book"].paydesc;
      this.detail.clicksCount = feed.entry["pris:subscribe"].clicksCount;
    },
  },
  activated() {
    this.booisAdd(this.booID);
    if (!this.$route.meta.isBack) {
      if (this.booID !== this.$route.query.sourceUuid) {
        this.booID = this.$route.query.sourceUuid;
      }
      this.getBookInfo();
      this.getComments();
      this.show = true;
      document.documentElement.scrollTop = 0;
    }
    this.$route.meta.isBack = false;
  },
  beforeRouteEnter(to, from, next) {
    if (from.name == "neirong") {
      to.meta.isBack = true;
    }

    next();
  },
};
</script>

<style lang="scss" scoped>
.wrapper {
  height: 100vh;
  background-color: #fff;
}

.bookinfo {
  padding: 60px 14px 0;
  background-color: #fff;
  overflow: hidden;
  .top {
    display: flex;
    .l {
      width: 110px;
      flex-shrink: 0;
      box-shadow: 2px 3px 4px #fafafa;
      img {
        width: 100%;
        height: 100%;
      }
    }
    .r {
      flex: 1;
      font-size: 16px;
      text-align: left;
      padding-left: 15px;
      .title {
        font-size: 18px;
        padding: 5px 0;
      }
      .author {
        padding: 10px 0;
        white-space: nowrap;
        overflow: hidden;
      }
      .rate {
      }
      .word {
        padding: 10px 0;
        .words {
          margin-right: 10px;
        }
        .clicks {
        }
      }
    }
  }
  .bottom {
    margin: 15px 0 0;
    font-size: 17px;
    text-align: left;
    border-bottom: 1px solid #eee;
    .content {
      padding-bottom: 2px;
      line-height: 1.5;
      position: relative;
      .van-icon {
        position: absolute;
        right: 5px;
        bottom: 5px;
        z-index: 22;
      }
    }
    .type {
      padding: 13px 0;
      color: #888;
      font-size: 16px;
    }

    .content.hidden {
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 3;
      overflow: hidden;
      text-overflow: ellipsis;
    }
  }
}
.mulu {
  height: 30px;
  display: flex;
  align-items: center;
  .l {
    height: 100%;
    margin-right: 10px;
  }
  .c {
    height: 100%;
    flex: 1;
    font-size: 15px;
    text-align: left;
    line-height: 30px;
  }
  .r {
    height: 100%;
    display: flex;
    font-size: 16px;
    align-items: center;
    div {
      color: rgb(47, 228, 11);
    }
  }
}
.comment {
  background-color: #fff;
  border-top: 10px solid #eee;
  padding: 0 14px 60px;
  .header {
    height: 50px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .l {
      padding-left: 10px;
      position: relative;
      font-size: 18px;
      &::before {
        position: absolute;
        left: 0;
        top: 50%;
        transform: translateY(-50%);
        content: "";
        display: block;
        width: 3px;
        height: 17px;
        background-color: #666;
      }
    }
    .r {
      border: 1px solid #000;
      font-size: 15px;
      padding: 5px 5px 5px 20px;
      box-sizing: border-box;
      border-radius: 5px;
      position: relative;
      .icon-xiepinglun {
        position: absolute;
        left: 3px;
        top: 20%;
        font-size: 24px;
        width: 20px;
      }
    }
  }
}
.write-comment {
  width: 100%;
  height: 100%;
  font-size: 16px;
  .write {
    border: 1px solid red;
    padding: 4px 15px;
    border-radius: 15px;
    margin-top: 10px;
    color: red;
  }
}
.all {
  display: inline-block;
  border: 1px solid #333;
  padding: 5px 20px;
  font-size: 18px;
  margin-bottom: 20px;
}
.write_comment {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
  padding: 14px;
  box-sizing: border-box;
  .write_content {
    overflow-y: scroll;
    width: 100%;
    height: 90px;
    margin: 14px 0;
    &::-webkit-scrollbar {
      display: none;
    }
    textarea {
      width: 100%;
      height: 100%;
      resize: none;
    }
  }
  .control {
    width: 100%;
    font-size: 16px;
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
}
</style>
